import os

from flask import Flask
from flask.logging import default_handler
from flask_cors import CORS

from . import cons, db
from .log import log

os.makedirs("%s" % cons.data_dir_path, mode=0o755, exist_ok=True)

db.try_init_db()


def create_app():
    log.info("create app")
    app = Flask(__name__,
                instance_path=os.path.abspath("./"),
                instance_relative_config=True,
                static_url_path='/static/',
                static_folder='./static',
                template_folder='./templates')

    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
    CORS(app, supports_credentials=True)

    # app.config.from_pyfile('config.py')

    app.logger.removeHandler(default_handler)
    app.logger = log

    try:
        os.makedirs(app.instance_path, mode=0o755, exist_ok=True)
    except OSError:
        log.exception("os error")

    @app.route('/ping')
    def hello():
        return 'pong'

    from . import service_common
    app.register_blueprint(service_common.bp)
    from . import service_dyb
    app.register_blueprint(service_dyb.bp)
    from . import service_user
    app.register_blueprint(service_user.bp)

    log.info("start")

    return app
